package com.example.week10_spring_security.controller;

import com.example.week10_spring_security.entity.Goods;
import com.example.week10_spring_security.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController("/goods")
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    @PostMapping("add")
    @PreAuthorize(value = "hasAuthority('goods:add')")
    public ResponseEntity<Void> addGoods(@RequestBody Goods goods) {
        goodsService.addGoods(goods);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('goods:delete')")
    public ResponseEntity<Void> deleteGoods(@PathVariable long id) {
        goodsService.deleteGoodsById(id);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/update")
    @PreAuthorize("hasAuthority('goods:update')")
    public ResponseEntity<Void> updateGood(@RequestBody Goods goods) {
        goodsService.updateGoods(goods);
        return ResponseEntity.ok().build();
    }

    @GetMapping(value="/{id}",produces="application/json;charset=UTF-8")
    public ResponseEntity<Goods> getGoods(@PathVariable long id) {
        Goods goods = goodsService.getGoodsById(id);
        return ResponseEntity.ok(goods);
    }

    @GetMapping(value="",produces="application/json;charset=UTF-8")
    public ResponseEntity<List<Goods>> listGoods() {
        List<Goods> goods = goodsService.getAllGoods();
        return ResponseEntity.ok(goods);
    }

    @GetMapping(value="/search",produces="application/json;charset=UTF-8")
    public ResponseEntity<List<Goods>> searchGoods(@RequestParam String name, @RequestParam double minPrice, @RequestParam double maxPrice) {
        List<Goods> goods = goodsService.getGoodsByNameAndPriceBetween(name, minPrice, maxPrice);
        return ResponseEntity.ok(goods);
    }

    @GetMapping(value="/suppliers/{id}",produces="application/json;charset=UTF-8")
    public ResponseEntity<List<Goods>> listGoodsBySupplierId(@PathVariable long id) {
        List<Goods> goods = goodsService.getGoodsBySupplierId(id);
        return ResponseEntity.ok(goods);
    }
}
